﻿using Chloe.SqlServer;
using KPI.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using TYBase;

namespace ScheduleManager.DB
{
    internal class DictDataDBHelper
    {
        public static R<List<Tbl_DictData>> GetList(string dict_type)
        {
            try
            {
                using (MsSqlContext dx = DBHelper.CreateWMSConnection())
                {
                    var listDict = dx.Query<Tbl_DictData>().Where(x => x.dict_type == dict_type).ToList();
                    return R<List<Tbl_DictData>>.OK(listDict);
                }

            }
            catch (Exception ex)
            {
                return R<List<Tbl_DictData>>.Fail(ex.Info());
            }

        }

        public static R<bool> AddList(List<Tbl_DictData> queryDto)
        {
            try
            {
                Dictionary<string, int> dictMax = new Dictionary<string, int>();
                using (MsSqlContext dx = DBHelper.CreateWMSConnection())
                {
                    foreach (var entity in queryDto)
                    {
                        if (!dictMax.ContainsKey(entity.dict_type))
                        {
                            int dict_value = 0;
                            if (dx.Query<Tbl_DictData>().Where(x => x.dict_type == entity.dict_type).Any())
                            {
                                dict_value = dx.Query<Tbl_DictData>().Max(x => x.dict_value);
                            }
                            dictMax[entity.dict_type] = dict_value;
                        }
                        //if (dx.Query<Tbl_DictData>().Where(x => x.dict_type == item.dict_type && x.dict_label == item.dict_label))
                        //{ 

                        //}
                    }
                    List<Tbl_DictData> listData = new List<Tbl_DictData>();
                    foreach (var entity in queryDto)
                    {
                        if (dx.Query<Tbl_DictData>().Where(x => x.dict_type == entity.dict_type && x.dict_label == entity.dict_label).Any())
                        {
                            continue;
                        }
                        dictMax[entity.dict_type]++;
                        entity.dict_value = dictMax[entity.dict_type];
                        listData.Add(entity);

                    }
                    dx.BulkInsert(listData);
                    return R<bool>.OK();
                }

            }
            catch (Exception ex)
            {
                return R<bool>.Fail(ex.Info());
            }

        }
    }
}
